import numpy as np
import pandas as pd
from pandas import Series, DataFrame

df = DataFrame( {
    "data":[ "Symbol: appl Seqno: 0 Price: 1623", 
    "Symbol: appl Seqno: 1 Price: 1624", 
    "Symbol: appl Seqno: 0 Price: 1625", 
    "Symbol: appl Seqno: 1 Price: 1626", 
    "Symbol: appl Seqno: 0 Price: 1627" ]
} )

df["type"] = Series( [ "a" ] * df.size )
#print( df )
''' 为df添加一个列
                                data type
0  Symbol: appl Seqno: 0 Price: 1623    a
1  Symbol: appl Seqno: 1 Price: 1624    a
2  Symbol: appl Seqno: 0 Price: 1625    a
3  Symbol: appl Seqno: 1 Price: 1626    a
4  Symbol: appl Seqno: 0 Price: 1627    a
'''
df['type'] = df['type'].apply( str.upper )
#print( df )
''' 使用apply，将type一列的内容改为大写
    apply可接受一个函数作为参数，这一点和map有点相似
                                data type
0  Symbol: appl Seqno: 0 Price: 1623    A
1  Symbol: appl Seqno: 1 Price: 1624    A
2  Symbol: appl Seqno: 0 Price: 1625    A
3  Symbol: appl Seqno: 1 Price: 1626    A
4  Symbol: appl Seqno: 0 Price: 1627    A
'''
def foo( line ):
    arr = line.split( " " )
    return Series( [ arr[1], arr[3], arr[5] ] )

df_tmp = df["data"].apply( foo )
df_tmp = df_tmp.rename( columns = { 0:"Symbol", 1:"Segno", 2:"Price" } )
print( df_tmp )
print( df )
# 等于说，现在有两个矩阵了，可以使用 combine_first 进行连接
# 不能使用 concat 进行拼接，因为它会把行列全部拼接起来
df = df.combine_first( df_tmp )
print( df )
''' 成功将data列的内容拆分出来
    Price  Segno Symbol                               data type
0  1623.0    0.0   appl  Symbol: appl Seqno: 0 Price: 1623    A
1  1624.0    1.0   appl  Symbol: appl Seqno: 1 Price: 1624    A
2  1625.0    0.0   appl  Symbol: appl Seqno: 0 Price: 1625    A
3  1626.0    1.0   appl  Symbol: appl Seqno: 1 Price: 1626    A
4  1627.0    0.0   appl  Symbol: appl Seqno: 0 Price: 1627    A
'''
# 去掉不需要使用的数据
df = df[ [ "Price", "Segno", "Symbol" ] ]
print( df )
'''
    Price  Segno Symbol
0  1623.0    0.0   appl
1  1624.0    1.0   appl
2  1625.0    0.0   appl
3  1626.0    1.0   appl
4  1627.0    0.0   appl
'''
df.to_csv( "C:\\Users\\新颜\\Desktop\\python测试\\test.csv", index = False )